package com.oobi.showlive.cloudsql.service.reg;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.oobi.showlive.cloudsql.data.conn.DBConnection;

public class Register extends HttpServlet {
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
			resp.setContentType("text/plain");
		    PrintWriter out = resp.getWriter();
			
			 // Get the user's name and password
		    String name = req.getParameter("name");
		    String passwd = req.getParameter("passwd");
		    if(notEmpty(name) && notEmpty(passwd)) {
		        try {
		        	Connection conn = DBConnection.getConnection();
		        	String statement = "INSERT INTO entries (username, password) VALUES( ? , ? )";
		            PreparedStatement stmt = conn.prepareStatement(statement);
		            stmt.setString(1, name);
		            stmt.setString(2, passwd);
		            int success = 2;
		            success = stmt.executeUpdate();
		            if (success == 1) {
		              out.println("Success!");
		            } else if (success == 0) {
		              out.println("Failure! Please try again!");
		            }
		        } catch(Exception e) {
		        	resp.sendError(HttpServletResponse.SC_EXPECTATION_FAILED);
		        } finally {
		            DBConnection.closeConnection();
		        }
		    } else {
		    	resp.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE);
		    }
	}
	
	 protected boolean notEmpty(String str) {
		    if(str!=null && !"".equals(str) )
		    	return true;  
		    else 
		    	return false;
      }
}
